using System;
using System.Collections.Generic;
using System.Text;

using System.Data;
using System.Data.SqlClient;

namespace DataAccessLayer
{
    public class RecordingGateway
    {
        private SqlConnection connection;
        private SqlCommand command;
        private SqlDataAdapter adapter;
        private SqlCommandBuilder builder;

        public RecordingGateway(SqlConnection connection)
        {
            this.connection = connection;
            command = new SqlCommand("SELECT * FROM Recording WHERE id=@id", connection);
            command.Parameters.Add("@id", SqlDbType.BigInt);
            adapter = new SqlDataAdapter(command);
            builder = new SqlCommandBuilder(adapter);

        }

        public long Insert(string title, DateTime releaseDate, long artistId, long labelId, RecordingDataSet recordingDataSet){
            RecordingDataSet.RecordingRow newRow = recordingDataSet.Recording.NewRecordingRow();
            newRow.id = IdGenerator.GetNextId(recordingDataSet.Recording.TableName, connection);
            newRow.title = title;
            newRow.releasedate = releaseDate;
            newRow.artistid = artistId;
            newRow.labelid = labelId;
            recordingDataSet.Recording.AddRecordingRow(newRow);
            Update(recordingDataSet);
            return newRow.id;

        
        }

        public RecordingDataSet.RecordingRow FindById(long id, RecordingDataSet recordingDataSet)
        {
            command.Parameters["@id"].Value = id;
            adapter.Fill(recordingDataSet, recordingDataSet.Recording.TableName);
            DataRow[] rows = recordingDataSet.Recording.Select(String.Format("id={0}", id));
            if (rows.Length < 1) return null;
            return (RecordingDataSet.RecordingRow)rows[0];
        }

        public void Delete(long deletedId, RecordingDataSet recordingDataSet)
        {
            RecordingDataSet.RecordingRow row = FindById(deletedId, recordingDataSet);
            row.Delete();
            Update(recordingDataSet);
        }

        public void Update(RecordingDataSet recordingDataSet)
        {
            adapter.Update(recordingDataSet, recordingDataSet.Recording.TableName);
        }
    }
}
